<?php
session_start(); // 启用Session
require_once __DIR__.'/../../utils/checkTokenUtils.php';
require_once __DIR__.'/../../utils/MysqlDBUtils.php';
use utils\MysqlDBUtils;

// 获取来源页面信息
$referer = $_SERVER['HTTP_REFERER'] ?? '';
// 从URL中获取category_id
$urlComponents = parse_url($referer);
parse_str($urlComponents['query'] ?? '', $queryParams);
$categoryId = isset($queryParams['category_id']) ? intval($queryParams['category_id']) : null;

// 仅允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die("错误：仅支持POST请求");
}

// 初始化数据库连接
$dbUtil = new MysqlDBUtils();

// 获取并验证表单数据
$id= isset($_POST['id'])? intval($_POST['id']) : 0;
$isbn = isset($_POST['isbn']) ? trim($_POST['isbn']) : '';
$title = isset($_POST['title']) ? trim($_POST['title']) : '';
$author = isset($_POST['author']) ? trim($_POST['author']) : '';
$publisher = isset($_POST['publisher']) ? trim($_POST['publisher']) : '';
$publishDate = isset($_POST['publish_date']) ? trim($_POST['publish_date']) : '';
$price = isset($_POST['price']) ? trim($_POST['price']) : '';
$stock = isset($_POST['stock']) ? trim($_POST['stock']) : '';

// 验证必填字段
if (empty($id) || empty($isbn) || empty($title) || empty($author)) {
    http_response_code(400);
    die("必填字段（id、ISBN、书名、作者）不能为空");
}

// 转义数据防止SQL注入
$escapedIsbn = $dbUtil->escapeString($isbn);
$escapedTitle = $dbUtil->escapeString($title);
$escapedAuthor = $dbUtil->escapeString($author);
$escapedPublisher = $dbUtil->escapeString($publisher);
$escapedPublishDate = $dbUtil->escapeString($publishDate);
$escapedPrice = $dbUtil->escapeString($price);
$escapedStock = $dbUtil->escapeString($stock);

// 构建更新SQL
$updateSql = "UPDATE book SET 
    title = '$escapedTitle',
    author = '$escapedAuthor',
    publisher = '$escapedPublisher',
    publish_date = '$escapedPublishDate',
    price = '$escapedPrice',
    stock = '$escapedStock'
WHERE id = $id"; // 确保 id 正确传入


// 执行更新
$result = $dbUtil->prepareQuery($updateSql);

if ($result !== false) {
    // 更新成功时存储提示信息到Session
    $_SESSION['success_message'] = '图书信息修改成功！';
} else {
    $_SESSION['error_message'] = '错误：数据库更新失败';
}

// 根据来源页面进行重定向
if (strpos($referer, 'BookCategory.php') !== false && $categoryId !== null) {
    $perPage = 8;
    header("Location: BookCategory.php?category_id=$categoryId&q=$q&page=$currentPage&per_page=$perPage");
} else {
    $perPage = 8;
    header("Location: Books.php?q=$q&page=$currentPage&per_page=$perPage");
}
exit;